import { makeAutoObservable } from 'mobx';
import * as api from './api';
import * as dict from '@/services/dict';
import { DATETIME_TEXT } from '@/stores/definitions-base';

class TableArgs {
  constructor(query) {
    this._args = {
      search: {},
      pg: {
        page: 0,
        sort: ['departureTime;desc', 'crDate;desc'],
        size: 10,
      },
    };
    this.loading = false;
    this.total = 0;
    this.dataSource = [];
    this.query = query;
    this.notReportDriver = {
      username: 'default@mzd',
      fullname: '未备案司机',
      phone: '00000000000',
      licenseNo: {
        mainland: '粤000000',
        hk: 'HK000000',
      },
      carrierVehicle: '00000000',
      hkPhone: '00000000000',
    };
    makeAutoObservable(this, {});
  }
  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}

export default class ScTaskStore {
  loadingLogs = false;
  loadingOrderLogs = false;
  companies = [];
  selectSettled = [];
  noticeUsers = [];

  startStations = [];
  endStations = [];
  shifts = [];


  _mainArgs = new TableArgs(this.query);
  _sendCarArgs = new TableArgs(this.querySendCarData);

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.dataSource = yield api.search({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  /**
 * @func 获取派车表格数据
 * @desc
 * @param {}
 */
  * querySendCarData(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.countSendCars(search);
      this.dataSource = yield api.searchSendCars(search, pg);
    } finally {
      this.loading = false;
    }
  }

  /**
   * @func 获取订单数据
   * @desc 根据订单id获取订单数据
   * @param {string} orderId 订单id
   * @return {object} 订单数据
   */
  * getOrderInfo(orderId) {
    return yield api.get(orderId);
  }

  /**
   * @func 获取任务数据
   * @desc 根据订单id获取订单数据
   * @param {string} orderId 订单id
   * @return {object} 订单数据
   */
  * getTaskInfo(taskId) {
    return yield api.getTaskInfo(taskId);
  }

  /**
   * @func 获取可以变更公司
   * @return {array} 公司列表
   */
  * taskListCompany(args) {
    return yield api.taskListCompany(args);
  }

  /**
   * @func 获取任务日志数据
   * @desc
   * @param {object} task 任务数据
   * @return {}
   */
  * getLogs(task) {
    const { driverInfo = [], id } = task || {};
    const workIdsOnlyOne = [...new Set(driverInfo.map(({ number }) => number))];
    const search = {
      targetIds: [...workIdsOnlyOne, id],
    };
    this.loadingLogs = true;
    try {
      return yield api.getLogs(search);
    } finally {
      this.loadingLogs = false;
    }
  }

  /**
   * @func 获取订单任务日志数据
   * @desc
   * @param {}
   * @return {}
   */
  * getOrderLogs(order) {
    const { taskIds: taskIdsTmp = [], id } = order;
    const taskIds = [...new Set(taskIdsTmp)];
    const orderSearch = {
      targetType: 'scOrder',
      targetIds: [...taskIds, id],
    };
    this.loadingOrderLogs = true;
    try {
      const orderLogs = yield api.getLogs(orderSearch);
      const taskLogs = [];
      for (const taskId of taskIds) {
        const taskInfo = yield api.getTaskInfo(taskId);
        const { driverInfo = [], carrierCompanyName, tickets = [] } = toJS(taskInfo);
        // 获取任务涉及的工单id
        const workOrderIds = driverInfo.reduce((res, cur) => {
          const { number } = cur;
          res.push(number);
          return res;
        }, []);

        const taskSearch = {
          targetIds: [...workOrderIds, taskId],
        };
        const taskLogsRes = yield api.getLogs(taskSearch);
        taskLogs.push({
          taskId,
          taskLog: toJS(taskLogsRes),
          companyName: carrierCompanyName,
          tickets,
        });
      }
      return { orderLogs, taskLogs };
    } finally {
      this.loadingOrderLogs = false;
    }
  }

  * getCompany(companyId) {
    return yield api.getCompany(companyId);
  }

  * company(args) {
    const res = yield api.company(args);
    return res.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  * transferCompanies() {
    const res = yield dict.getDictItem('dispatchH5Config', 'specialId');
    const { value } = res?.extras?.zgtId;
    return { [value]: true };
    // return res.reduce((acc, arr) => {
    //   const { name, id } = arr;
    //   acc[id] = name;
    //   return acc;
    // }, {});
  }

  * getNoticeUsers() {
    const res = yield dict.searchDictItem('ZGTAccountNoticeUsers');
    this.noticeUsers = res.map(({ name, fullId }) => ({
      label: name,
      value: fullId,
    }));
  }

  * alterationCompany(data) {
    yield api.alterationCompany(data);
    this._mainArgs.query();
  }

  * sendCar(data) {
    yield api.sendCar(data);
    this._mainArgs.query();
  }

  * update(task) {
    yield api.update(task);
    this._mainArgs.query();
  }

  * updatePrice(data) {
    yield api.updatePrice(data);
    this._mainArgs.query();
  }

  * changeTaskState(id, data) {
    yield api.changeTaskState(id, data);
    this._mainArgs.query();
  }

  * cancelSendCar(data) {
    yield api.cancelSendCar(data);
    this._mainArgs.query();
  }

  * getScOrders(args) {
    return yield api.getScOrders(args);
  }

  * getScOrdersInfo(args) {
    return yield api.getScOrdersInfo(args);
  }

  * taskRemoveOrder(args) {
    yield api.taskRemoveOrder(args);
  }

  * taskJoinOrder(args) {
    return yield api.taskJoinOrder(args);
  }

  async getCompanies() {
    const res = await api.company();
    this.companies = res.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  getDriverInfo(driverInfo = []) {
    if (driverInfo.length <= 0) return {};
    const curDriver = driverInfo.find((e) => e.state !== '0');
    return curDriver;
  }

  uniqueArray(arr) {
    const data = _.cloneDeep(arr);
    const resultTickets = [];
    const mapArr = new Map();
    data.forEach((p) => {
      if (!mapArr.has(`${p.fromStationName}:${p.toStationName}`)) {
        mapArr.set(`${p.fromStationName}:${p.toStationName}`, true);
        resultTickets.push(p);
      }
    });
    return resultTickets;
  }

  _copyTrip(info) {
    const res = this.transferTrip(info);
    const { departureTime, totalPrice } = toJS(info);
    const time =
      `
${DATETIME_TEXT(departureTime)}`;
    const price =
      `
费用：${totalPrice}`;
    const trips = res.reduce((acc, arr) => {
      const { startMainAreaText, fromStationName, fromStationAddress, endMainAreaText, toStationName, toStationAddress } = arr;
      acc += `
开始地址：${startMainAreaText}-${fromStationName}(${fromStationAddress})
结束地址：${endMainAreaText}-${toStationName}(${toStationAddress})
`;
      return acc;
    }, '');
    const _make = `${time}${trips}${price}`;
    return _make;
  }

  transferTrip(info) {
    const { tickets = [], orderBaseModel = {} } = toJS(info);
    const { startMainAreaText, endMainAreaText } = orderBaseModel;
    const cloneTickets = _.cloneDeep(tickets);
    const uniqueArr = this.uniqueArray(cloneTickets);
    const result = uniqueArr.map((p) => ({ ...p, startMainAreaText, endMainAreaText }));
    return result;
  }

  _copyDispatch(info) {
    const { driverInfo } = toJS(info);
    const _driverInfo = this.getDriverInfo(driverInfo);
    const {
      phone,
      licenseNo = '',
      hkPhone,
      name,
    } = _driverInfo || {};
    const [ld, hk] = licenseNo.split(' / ');
    const text =
      `
香港车牌：${hk}
国内车牌：${ld}
香港电话：${hkPhone}
国内电话：${phone}(${name})`;
    return text;
  }

  async getStartBusStation(args) {
    try {
      const res = await api.getBusStation(args);
      let stations = [];
      for (let i = 0; i < res.length; i++) {
        const e = res[i];
        stations = stations.concat([...e.children]);
      }
      this.startStations = stations.map(({ id, name }) => ({ label: name, value: id }));
    } catch (error) {
      console.error('获取始发巴士站点错误', error);
      throw error;
    }
  }

  async getEndBusStation(args) {
    try {
      const res = await api.getBusStation(args);
      let stations = [];
      for (let i = 0; i < res.length; i++) {
        const e = res[i];
        stations = stations.concat([...e.children]);
      }
      this.endStations = stations.map(({ id, name }) => ({ label: name, value: id }));
    } catch (error) {
      console.error('获取到达巴士站点错误', error);
      throw error;
    }
  }

  async getPrices(args) {
    try {
      return await api.getPrices({
        ...args,
      });
    } catch (error) {
      console.log('🚀 _ file: ScRelevancyStore.js:99 _ ScRelevancyStore _ error:', error);
      throw error;
    }
  }

  * servicesTicketIssue(args) {
    yield api.servicesTicketIssue(args);
    this._mainArgs.query();
  }

  async getServiceShifts(args) {
    try {
      const res = await api.getServiceShifts(args);
      this.shifts = res.map((p) => ({ ...p, label: `${args.departureDate} (${p.runTime} ~ ${p.endTime})`, value: p.id }));
    } catch (error) {
      console.error('获取第三方站点错误', error);
      throw error;
    }
  }

  async getUserInfo(args) {
    try {
      return await api.getUserInfo(args);
    } catch (error) {
      console.error('获取用户错误', error);
      throw error;
    }
  }

  transferTickets(ticket, orderInfo) {
    const parseTickets = toJS(ticket);
    const arr = [];
    for (let i = 0; i < parseTickets.length; i++) {
      const e = parseTickets[i];
      if (e.orderId === orderInfo.id) {
        arr.push({ ...e });
      }
    }
    return arr;
  }

  transferTicketsError(ticket, orderInfo) {
    const parseTickets = toJS(ticket);
    const arr = [];
    for (let i = 0; i < parseTickets.length; i++) {
      const e = parseTickets[i];
      if ((e.orderId === orderInfo.id) && (!e.operatingTicketCode) && (e.errorMsg) && (e.errorMsg !== '')) {
        arr.push({ ...e });
      }
    }
    return arr;
  }
}
